//
//  HTTPRequstManger.m
//  OverseasImmigration
//
//  Created by yuqin on 2019/5/20.
//  Copyright © 2019年 yuqin. All rights reserved.
//

#import "HTTPRequstManger.h"
#import "BaseService.h"

@implementation HTTPRequstManger
DEFINE_SINGLETON_FOR_CLASS(HTTPRequstManger);

-(NSURLSessionDataTask *)postRequestWithUrlString:(NSString*)urlString  appendParameters:(NSDictionary*)appendParameters  bodyParameters:(NSDictionary*)bodyParameters successBlock:(SZHTTPSuccessBlock)successBlock failureBlock:(SZHTTPFailureBlock)failureBlock{
    int i =0;
    NSString * parametersString = @"";
    for (NSString *strKey in [appendParameters allKeys])
    {
        NSString *strVal = [appendParameters objectForKey:strKey];
        
        if (i == 0) {
            parametersString = [NSString stringWithFormat:@"?%@=%@", strKey, strVal];
        } else {
            parametersString = [NSString stringWithFormat:@"%@&%@=%@", parametersString, strKey, strVal];
        }
        i++;
    }
    NSString *urlstr = [NSString stringWithFormat:@"%@%@", urlString,parametersString];
    urlstr = [urlstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];// 设置请求格式
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    manager.requestSerializer.timeoutInterval = SERVICETIMEOUT;
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"ClientType"];
//    [manager.requestSerializer setValue:language_sys forHTTPHeaderField:@"Accept-Language"];
    
    
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    [securityPolicy setValidatesDomainName:YES];
    manager.securityPolicy = securityPolicy;
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];// 设置返回格式
    NSLog(@"%@", [NSString stringWithFormat:@"\n<---------------------------------|start Request|--------------------------------->\nURL is :%@ \nBody is: %@", urlstr,bodyParameters]);
    NSURLSessionDataTask * task = [manager POST:urlstr parameters:bodyParameters progress:nil success:^(NSURLSessionDataTask *operation, id responseObject){
        
        if (successBlock){
            
            NSLog(@"\n\nResponse : %@\n<---------------------------------|End Request|--------------------------------->", [responseObject mj_JSONString]);
            
            BaseModel * base = [BaseModel modelWithJson:responseObject];
            if (base.code == 500) {
                if (failureBlock){
                    failureBlock([self errorWithCode:base.code]);
                }
            }else{
                successBlock(responseObject);
                if (base.code == -100) {
                    
                }
                
            }
        }
    }failure:^(NSURLSessionDataTask *operation, NSError *error){
        DLog(@"error:%@",error);
        if (failureBlock){
            failureBlock([self errorWithCode:error.code]);
        }
    }];
    return task;
}


-(NSURLSessionDataTask *)getRequestWithUrlString:(NSString*)urlString  appendParameters:(NSDictionary*)appendParameters successBlock:(SZHTTPSuccessBlock)successBlock failureBlock:(SZHTTPFailureBlock)failureBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];// 设置请求格式
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    manager.requestSerializer.timeoutInterval = SERVICETIMEOUT;
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//    [manager.requestSerializer setValue:language_sys forHTTPHeaderField:@"Accept-Language"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//    [manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"ClientType"];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];// 设置返回格式
    
    NSLog(@"%@", [NSString stringWithFormat:@"\n<---------------------------------|start Request|--------------------------------->\nURL is :%@ \nParameters is: %@ --------------------------------->", urlString,appendParameters]);
    if (isEmptyObject(appendParameters)) {
        appendParameters=[NSDictionary new];
    }
    NSURLSessionDataTask * _Nullable extractedExpr = [manager GET:urlString parameters:appendParameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (successBlock){
            
            NSLog(@"\n\nResponse : %@\n<---------------------------------|End Request|--------------------------------->", [responseObject mj_JSONString]);
            
            BaseModel * base = [BaseModel modelWithJson:responseObject];
            if (base.code == 500) {
                if (failureBlock){
                    failureBlock([self errorWithCode:base.code]);
                }
            }else{
                successBlock(responseObject);
                if (base.code == -100) {
//                    [UserInfo sharedUserInfo].bIsLogin = NO;
//                    self.presentLoginVC(responseObject);
                }
                
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DLog(@"error:%@",error);
        if (failureBlock){
            failureBlock([self errorWithCode:error.code]);
        }
    }];
    NSURLSessionDataTask * task = extractedExpr;
    return task;
}

- (NSError *)errorWithCode:(NSInteger)code {
    
    NSString *message = @"网络太慢了，请稍后重试";
    switch (code) {
        case NSURLErrorBadServerResponse :
            message =  NSLocalizedString(@"接口服务异常", nil);
            break;
    }
    //    switch (code) {
    //        case NSURLErrorCancelled:
    //            message = NSLocalizedString(@"网络请求取消", nil) ;
    //            break;
    //        case NSURLErrorNetworkConnectionLost:
    //            message =  NSLocalizedString(@"网络已断开,请检查您的网络连接", nil);
    //            break;
    //        case NSURLErrorNotConnectedToInternet:
    //            message =  NSLocalizedString(@"似乎已断开与互联网的连接", nil);
    //            break;
    //        case NSURLErrorCannotFindHost:
    //            message =  NSLocalizedString(@"无法连接服务器,请稍后重试", nil);
    //            break;
    //        case NSURLErrorTimedOut:
    //            message =  NSLocalizedString(@"请求超时,请稍后重试", nil);
    //            break;
    //        case NSURLErrorCannotConnectToHost:
    //            message =  NSLocalizedString(@"未能连接到服务器", nil);
    //            break;
    //        case NSURLErrorBadServerResponse :
    //            message =  NSLocalizedString(@"网络接口出现异常", nil);
    //            break;
    //        case 500:
    //            message =  NSLocalizedString(@"后台接口程序异常", nil);
    //            break;
    //    }
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    userInfo[NSLocalizedDescriptionKey] = message;
    NSError *error = [NSError errorWithDomain:@"Error" code:code userInfo:userInfo];
    
    return error;
}

@end
